package com.faya.green.service.impl;

import com.faya.green.abnormal.ServiceException;
import com.faya.green.common.Constant;
import com.faya.green.dao.user.PunishDao;
import com.faya.green.dao.user.UserDao;
import com.faya.green.enumeration.StatusEnum;
import com.faya.green.model.Punish;
import com.faya.green.model.User;
import com.faya.green.service.PunishService;
import com.faya.green.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ：LX
 * 创建时间： 2018/8/24. 21:03
 * 地点：广州
 * 目的:
 * 备注说明：
 */
@Service
public class PunishServiceImpl implements PunishService {

    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private PunishDao punishDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePunish(Punish punish) {
        if (CommonUtils.checkNull(punish.getUserId())){
            throw new ServiceException("用户ID找不到");
        }
        punish.setStatus(StatusEnum.STATUS_UPDATE.getCode());
        punish.setUpdateTime(new Date());

        punishDao.updatePunish(punish);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPunish(Punish punish) {
        if (CommonUtils.checkNull(punish.getUserId())){
            throw new ServiceException("用户ID找不到");
        }
        User user = userDao.findUserById(punish.getUserId());
        if (user == null){
            throw new ServiceException("找不到用户");
        }
        user.setIsPunish(Constant.YES);
        userDao.updateUser(user);

        punish.setStatus(StatusEnum.STATUS_ADD.getCode());
        punish.setId(UUID.randomUUID().toString());
        punish.setCreateTime(new Date());
        punish.setUpdateTime(new Date());

        punishDao.addPunish(punish);
    }

    @Override
    public Punish getPunishById(String id) {
        return punishDao.getPunishById(id);
    }

    @Override
    public List<Punish> getPunishByUserIdPubilc(String userId, String isPubilc) {
        return punishDao.getPunishByUserIdPubilc(userId, isPubilc);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delPunish(String id) {
        Punish punish = punishDao.getPunishById(id);
        if (punish != null){
            String userId = punish.getUserId();
            List<Punish> punishList = punishDao.getPunishByUserIdPubilc(userId, null);
            if (punishList.size() == 0 || punishList.size() == 1){
                User user = userDao.findUserById(userId);
                user.setIsPunish(Constant.NO);
                userDao.updateUser(user);
            }
        }
        punishDao.delPunish(id);
    }
}
